import { deleteItem, selectById, selectPage } from '@/services/goods/supplier';
import { isShowButton } from '@/utils/util';
import { ProTable } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';

import { useDispatch, useSelector } from '@umijs/max';
import { Button, Modal } from 'antd';
import { Fragment, useEffect, useRef } from 'react';
import Details from './Details';
import { columns } from './columns';
import './index.less';

const currentPermissions = JSON.parse(localStorage.getItem('currentPermissions'));

export default () => {
  const ref = useRef();
  const dispatch = useDispatch();
  const { reload, userList } = useSelector((state) => state.supplier);
  const update = (data) => {
    dispatch({
      type: 'supplier/update',
      payload: data,
    });
  };

  useEffect(() => {
    dispatch({ type: 'supplier/getUserList' });
    dispatch({ type: 'commonInterface/getTreeList' });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 新增编辑刷新分页
  useEffect(() => {
    if (reload) {
      ref?.current?.reload();
      dispatch({ type: 'supplier/getUserList' });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [reload]);

  // 详情接口
  const { run: mutateAsync } = useRequest(
    selectById,
    {
      manual: true,
      onSuccess: ({ code, data }) => {
        if (code && code === 200) {
          update({
            visible: true,
            queryInfo: {
              ...data,
            },
          });
        }
      },
    }
  );

  // 删除接口
  const { run: mutateDeleteAsync } = useRequest(
    deleteItem,
    {
      manual: true,
      onSuccess: (data) => {
        if (data?.code && data?.code === 200) {
          ref?.current?.reload();
          dispatch({
            type: 'supplier/getUserList',
            payload: {},
          });
        }
      },
    }
  );

  // 操作
  const handleEdit = (type, record) => {
    update({ type });
    if (type === 'add') {
      update({ visible: true, queryInfo: { type: 0 } });
    }
    if (type === 'edit') {
      mutateAsync({ id: record.supplierId });
    }
    if (type === 'delete') {
      if (record?.flag) {
        Modal?.error({
          title: '无法删除',
          content: '该供应商已关联商品，无法删除',
          maskClosable: true,
        });
        return;
      }
      Modal?.confirm({
        title: '温馨提示',
        content: '确定是否删除该供应商？',
        maskClosable: true,
        autoFocusButton: null,
        cancelText: '取消',
        okText: '确定',
        onOk: () =>
          mutateDeleteAsync({
            id: record.supplierId,
            productId: record?.productId,
            supplierId: record?.supplierId,
          }),
      });
    }
  };
  return (
    <Fragment>
      <ProTable
        headerTitle="供应商列表"
        actionRef={ref}
        options={false}
        defaultSize="small"
        form={{
          defaultCollapsed: false,
        }}
        search={{
          labelWidth: 'auto',
          style: {
            padding: '24px 12px',
          },
        }}
        request={async (params = {}) => {
          const { current, pageSize, ...formData } = params;
          let body = {
            ...formData,
            pageNum: current,
            pageSize,
          };
          const { code, data, total } = await selectPage(body);
          if (code && code === 200) {
            update({ reload: false });
            return {
              data: data || [],
              total: total,
              success: true,
            };
          }
        }}
        toolBarRender={() => [
          <>
            {isShowButton(currentPermissions, 'product:supplier:add') && (
              <Button key="add" type="primary" onClick={() => handleEdit('add')}>
                新增供应商
              </Button>
            )}
          </>,
        ]}
        pagination={{
          showSizeChanger: true,
        }}
        cardProps={{
          size: 'small',
          style: {
            padding: 0,
          },
        }}
        cardBordered={true}
        columns={columns({
          handleEdit,
          productSelector: {
            options: userList.map((item) => ({
              label: item.productSelector,
              value: item.productId,
            })),
          },
          currentPermissions,
        })}
        rowKey="supplierId"
        scroll={{ x: 1300 }}
      />
      <Details />
    </Fragment>
  );
};
